using UnityEngine;
using UnityEngine.UI;
using System.Collections;

/// <summary>
/// 文字打印效果控制器
/// 实现文字逐个显示的打字机效果
/// </summary>
public class TypewriterEffect : MonoBehaviour
{
    [Tooltip("文字显示速度（字符/秒）")]
    public float printSpeed = 30f; // 文字显示速度

    [Tooltip("是否在启用时自动开始打印")]
    public bool autoStart = true; // 是否自动开始

    [Tooltip("开始打印前的延迟时间（秒）")]
    public float startDelay = 0f; // 开始延迟

    [Tooltip("文字打印完成后的回调事件")]
    public UnityEngine.Events.UnityEvent onPrintComplete; // 打印完成事件

    private Text targetText; // 目标文本组件
    private string fullText; // 完整文本内容
    private Coroutine printCoroutine; // 打印协程
    private bool isPrinting = false; // 是否正在打印

    /// <summary>
    /// 组件启用时调用
    /// </summary>
    private void OnEnable()
    {
        targetText = GetComponent<Text>();
        if (targetText == null)
        {
            Debug.LogError("TypewriterEffect: 未找到Text组件");
            enabled = false;
            return;
        }

        // 保存完整文本并清空显示
        fullText = targetText.text;
        targetText.text = "";

        if (autoStart)
        {
            StartPrinting();
        }
    }

    /// <summary>
    /// 开始打印文字
    /// </summary>
    public void StartPrinting()
    {
        if (isPrinting)
        {
            StopPrinting();
        }

        printCoroutine = StartCoroutine(PrintTextCoroutine());
    }

    /// <summary>
    /// 停止打印文字
    /// </summary>
    public void StopPrinting()
    {
        if (printCoroutine != null)
        {
            StopCoroutine(printCoroutine);
            printCoroutine = null;
            isPrinting = false;
        }
    }

    /// <summary>
    /// 立即显示所有文字
    /// </summary>
    public void ShowAllText()
    {
        StopPrinting();
        targetText.text = fullText;
        onPrintComplete?.Invoke();
    }

    /// <summary>
    /// 文字打印协程
    /// </summary>
    private IEnumerator PrintTextCoroutine()
    {
        isPrinting = true;
        targetText.text = "";

        // 等待开始延迟
        if (startDelay > 0)
        {
            yield return new WaitForSeconds(startDelay);
        }

        // 逐个字符显示文字
        for (int i = 0; i < fullText.Length; i++)
        {
            targetText.text += fullText[i];
            // 控制打印速度
            yield return new WaitForSeconds(1f / printSpeed);
        }

        isPrinting = false;
        // 触发完成事件
        onPrintComplete?.Invoke();
    }
}